<?php
require_once ('library/Smithy/Image/Abstract.php');

/**
 * Class for handling jpg images.
 *
 * Uses the GD PHP extension.
 *
 * @author Kovács Tamás
 * @category Smithy
 * @package Smithy_Image
 */
class Smithy_Image_Jpg extends Smithy_Image_Abstract
{
    protected $_quality = 80;


    /**
     * Constructor
     *
     * @param string $fileName
     * @param int $quality Between 0 and 100
     */
    public function __construct($fileName = null, $quality = 80)
    {
        parent::__construct($fileName);
        $this->setQuality($quality);
    }

    /**
     * Sets the jpeg quality.
     *
     * @param int $quality Between 0 and 100
     * @return Smithy_Image_Jpg
     */
    public function setQuality($quality)
    {
        $quality = (int)$quality;
        $this->_quality = $quality > 100 ? 100 : ($quality < 0 ? 0 : $quality);
        return $this;
    }

    /**
     * @see Smithy_Image_Abstract::_loadImageFromFile()
     *
     * @return Smithy_Image_Jpg
     */
    protected function _loadImageFromFile ()
    {
        $this->_imageResource = imagecreatefromjpeg($this->_fileName);
        if (false === $this->_imageResource) {
            throw new Exception('Could not load image from file: ' . $this->_fileName);
        }

        $this->_loadImageSize();
        return $this;
    }

    /**
     * @see Smithy_Image_Abstract::save()
     *
     * @param string $destination [OPTIONAL]
     * @return bool
     */
    public function save($destination = null)
    {
        if (null !== $destination) {
            $this->setDestination($destination);
        }
        imagejpeg($this->_imageResource, $this->_destination, $this->_quality);
        return $this;
    }
}
